﻿using SqlSugar;
 
using Zhaoxi.SqlSugar.Models;

namespace Zhaoxi.NET7Demo
{
    /// <summary>
    /// 自定义分表
    /// </summary>
    public static class CustomSubTableDemo
    {

        public static void ShowCustomSubTable()
        {
            var connectionconfig = new ConnectionConfig()
            {
                DbType = DbType.SqlServer,
                ConnectionString = "Data Source=PC-202206030027;Initial Catalog=CustomDBInfo;Persist Security Info=True;User ID=sa;Password=sa123",
                IsAutoCloseConnection = true,
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    SplitTableService = new AreaSubTableService() //让分表规则生效
                }
            };
            using (SqlSugarClient db = new SqlSugarClient(connectionconfig))
            {
                //db.CurrentConnectionConfig.ConfigureExternalServices.SplitTableService = new AreaSubTableService();
                db.CodeFirst
                   .SplitTables()//标识分表
                    .InitTables<CommoditySubTableDayArea>(); //程序启动时加这一行,如果一张表没有会初始化一张

               

                List<CommoditySubTableDayArea> addmodelList = new List<CommoditySubTableDayArea>();
                for (int i = 0; i < 10; i++)
                {
                    foreach (var dic in AreaSubTableService._AreaDictionary)
                    {
                        addmodelList.Add(new CommoditySubTableDayArea()
                        {
                            CategoryId = 1,
                            Createtime = DateTime.Now,
                            ImageUrl = $"Images_{i}",
                            Price = 345,
                            ProductId = i,
                            Province = dic.Value,
                            Title = "这里是一条测试数据",
                            Url = "URL"
                        });
                    }
                }

                db.Insertable(addmodelList).SplitTable().ExecuteCommand();
                //只查A表
                var listall = db.Queryable<CommoditySubTableDayArea>().Where(it => it.Province.Contains("湖北")).SplitTable(tas => tas.ContainsTableNames("_Area_")).ToList();
            }
        }
    }
}
